/*
 * NewGoodsPresenter.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.newgoods;

import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.model.IHomeModel;
import com.yidiandao.business.data.recyclertype.DoubleGoods;
import com.yidiandao.business.ui.widget.view.SuperLoadingLayout;

import java.util.List;

/**
 * 首页-最新商品-Presenter
 */
public class NewGoodsPresenter implements NewGoodsContract.Presenter {

    private NewGoodsContract.View mNewGoodsView;

    private IHomeModel mModel;

    private List<Goods> mGoodsList;

    private List<DoubleGoods> mGoodsGridList;

    private boolean isGridStyle;

    private boolean mEmptyResult;

    private boolean mHasMoreData;

    public NewGoodsPresenter(NewGoodsContract.View view, IHomeModel model) {
        mNewGoodsView = view;
        mModel = model;

        mNewGoodsView.setPresenter(this);
    }

    @Override
    public void start() {
        loadNewGoodsList(true);
    }

    @Override
    public void loadNewGoodsList(final boolean isRefreshing) {

        mModel.loadNewGoodsList(isRefreshing, mNewGoodsView.getPagerTag(), new IHomeModel.OnLoadGoodsListener() {
            @Override
            public void onSuccess(List<Goods> goodsList, List<DoubleGoods> goodsGridList, boolean emptyResult, boolean hasMoreData) {
                if (isRefreshing) {
                    mNewGoodsView.refreshContent(mNewGoodsView.checkResultObject(goodsGridList));
                    mNewGoodsView.setRefreshComplete();
                }

                mGoodsList = goodsList;
                mGoodsGridList = goodsGridList;

                mEmptyResult = emptyResult;
                mHasMoreData = hasMoreData;

                refreshStyleUI(isGridStyle);
            }

            @Override
            public void onFailed() {
                if (isRefreshing) {
                    mNewGoodsView.refreshContent(SuperLoadingLayout.STATE_ERROR);
                } else {
                    mNewGoodsView.loadMoreError();
                }
            }
        });
    }

    @Override
    public void changeStyle(boolean isGridStyle) {
        this.isGridStyle = isGridStyle;
        refreshStyleUI(isGridStyle);
    }

    private void refreshStyleUI(boolean isGridStyle) {
        if (isGridStyle) {
            // 当前是网格状
            mNewGoodsView.setGoodsList(mGoodsList);
        } else {
            mNewGoodsView.setGoodsGrid(mGoodsGridList);
        }
        refreshLoadMoreState();
    }

    private void refreshLoadMoreState() {
        mNewGoodsView.loadMoreFinish(mEmptyResult, mHasMoreData);
    }
}
